<template>
  <div>
    <Header :title="'返回'" :subTitle="'主题活动列表'" :hasBackPath="true" @headerBack="headerBack"></Header>
    <a-spin :spinning="spinning" size="large">
      <a-card :bordered="false">
        <div class="steps-head">
          <a-steps :current="current" size="small">
            <a-step v-for="item in steps" :key="item.title" :title="item.title" />
          </a-steps>
        </div>
        <div class="steps-content">
          <section v-show="current == 0">
            <a-form-model ref="rulesForm" :model="form" :rules="rules" :labelCol="{ lg: { span: 5 }, sm: { span: 7 } }" :wrapperCol="{ lg: { span: 10 }, sm: { span: 17 } }">
              <a-form-model-item label="活动名称" prop="activityName">
                <a-input v-model="form.activityName" placeholder="请输入" :max-length="20" />
              </a-form-model-item>
              <a-form-model-item label="活动时间" prop="timePicker">
                <a-range-picker style="width:100%;" :show-time="{ format: 'HH:mm:ss' }" :placeholder="['开始时间', '结束时间']" v-model="form.timePicker" @change="onChange" @ok="onOk" />
              </a-form-model-item>
              <a-form-model-item label="封面图" prop="imgList">
                <JImageUpload :uploadParams="getUploadParams()" :fileSize="0.5" :accept="'image/*'" :isMultiple="false" @fileChange="fileImageChange" v-model="imgList"></JImageUpload>
                <div class="upload__tip" style="line-height: 16px;">885x540，支持jpg/png/gif格式，文件大小不超过500k</div>
              </a-form-model-item>
              <a-form-model-item
                :label="index == 0 ? '参与活动品牌' : ''"
                v-for="(brand, index) in form.brands"
                :prop="'brands.' + index"
                :key="index"
                :rules="{ required: true, trigger: ['change', 'blur'], validator: (rule, value, callback) => validatorbrands(rule, brand, callback) }"
                :labelCol="{ lg: { span: 5 }, sm: { span: 7 } }"
                :wrapperCol="index === 0 ? { lg: { span: 10 }, sm: { span: 17 } } : { lg: { span: 10 }, sm: { span: 17, offset: 5 } }"
              >
                <a-select :value="brand" show-search :filter-option="filterOption" style="width:90%;margin-right:12px;" @change="e => handleSelectChange(e, index)">
                  <a-select-option :value="item.value" v-for="item in brandsList" :key="item.value">
                    {{ item.name }}
                  </a-select-option>
                </a-select>
                <a-icon v-if="form.brands.length > 1" class="dynamic-delete-button" type="minus-circle-o" :disabled="form.brands.length === 1" @click="removeBrands(brand, index)" />
              </a-form-model-item>
              <a-form-model-item :wrapperCol="{ lg: { span: 10 }, sm: { span: 17, offset: 5 } }">
                <a-button type="dashed" @click="addBrands" style="margin:0 auto;"> <a-icon type="plus" /> 添加品牌</a-button>
              </a-form-model-item>
              <a-form-model-item label="排序值" prop="sortNo">
                <a-input v-model="form.sortNo" placeholder="请输入" :maxLength="3" />
              </a-form-model-item>
              <a-form-model-item label="小程序首页展示" required>
                <a-switch v-model="form.miniAppShow" />
              </a-form-model-item>
            </a-form-model>
          </section>
          <section v-show="current == 1">
            <a-form-model-item label="微信素材" prop="material" required>
              <div class="xcx">
                <a-card hoverable v-show="form.materialId" class="xcx-card">
                  <img slot="cover" :src="xcxImg" alt="" class="img-cover" />
                  <a-card-meta>
                    <template slot="title">
                      <ellipsis :length="20" tooltip>{{ xcx.createTime }}</ellipsis>
                    </template>
                    <template slot="description">
                      {{ xcxText }}
                    </template>
                  </a-card-meta>
                </a-card>
                <a-button @click="openMaterial">选择微信素材</a-button>
                <span v-show="showwxTip && !form.materialId" class="tip">请选择微信素材</span>
              </div>
            </a-form-model-item>
          </section>
        </div>
        <div class="steps-action">
          <a-button v-if="current < steps.length - 1" type="primary" @click="next">
            下一步
          </a-button>
          <a-button v-if="current > 0" style="margin-left: 8px" @click="prev">
            上一步
          </a-button>
          <a-button v-if="current == steps.length - 1" type="primary" @click="submit" style="margin-left:18px">
            保存
          </a-button>
          <a-button v-if="current == steps.length - 1" type="primary" @click="submitAndKeep" style="margin-left:18px">
            保存，继续添加搭配
          </a-button>
        </div>
        <MaterialModal ref="materialModal" @getChoose="getChoose"></MaterialModal>
      </a-card>
    </a-spin>
  </div>
</template>
<script>
import moment from 'moment'
import 'moment/locale/zh-cn'
import globalData from '@/assets/js/common'
import Header from '@/views/box/components/layouts/Header'
import JImageUpload from '@/components/qiniuUpload/JImageUpload.vue'
import MaterialModal from '@/views/box/components/wxMaterialModal'
import { themeMixin } from './util/mixin'
import { Ellipsis } from '../../components'
import { addThemeActivity, editThemeActivityById, validCanDelBrand } from '@/api/box/theme'
export default {
  mixins: [themeMixin],
  components: { Header, JImageUpload, MaterialModal, Ellipsis },
  data() {
    return {
      moment,
      themeId: '',
      current: 0,
      steps: [
        { title: '活动设置', content: 'First-content' },
        { title: '分享设置', content: 'Second-content' }
      ],
      form: {
        activityName: '',
        timePicker: undefined,
        imgList: [],
        brands: [],
        sortNo: '',
        miniAppShow: false
      },
      rules: {
        activityName: [{ required: true, message: '请输入活动名称，最多20个字', trigger: 'blur', max: 20 }],
        timePicker: [{ required: true, message: '请选择活动时间', trigger: ['change', 'blur'] }],
        imgList: [{ required: true, message: '请上传封面图', trigger: ['blur', 'change'], validator: this.validatorImg, type: 'array' }],
        sortNo: [{ required: true, message: '请输入排序值，且为数字', trigger: 'blur', pattern: /^[1-9]\d*$/ }]
      },
      imgList: [],
      xcx: {},
      xcxImg: '',
      xcxText: '',
      showwxTip: false,
      materialList: [],
      spinning: false,
      originBrands: []
    }
  },
  beforeRouteLeave(to, from, next) {
    this.$destroy()
    next()
  },
  activated() {
    this.initialPage()
  },
  methods: {
    // 初始化页面
    async initialPage() {
      // await this.fetchMaterialList()
      this.themeId = this.$route.params.id
      if (this.themeId != 'add') {
        this.fetchActivityDetail()
      } else {
        this.form.brands = ['']
        this.$forceUpdate()
      }
    },
    next() {
      this.$refs.rulesForm.validate(valid => {
        if (valid) {
          let list = Array.from(new Set(this.form.brands))
          this.form.brands = list
          this.current++
        }
      })
    },
    prev() {
      this.current--
    },
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    async handleSelectChange(value, index) {
      console.log(this.form)
      if (this.originBrands.indexOf(value) > -1) {
        this.$message.warning('该品牌已存在！')
        return
      }
      if (this.themeId != 'add') {
        console.log(this.originBrands)
        if (this.originBrands[index]) {
          let result = await this.getValidCanDelBrand(this.originBrands[index])
          if (!result) {
            this.$message.warning('该品牌下已有关联搭配！')
            return
          }
        }
      }
      this.form.brands[index] = value
      this.originBrands = JSON.parse(JSON.stringify(this.form.brands))
      this.$forceUpdate()
    },
    getValidCanDelBrand(id) {
      let params = {
        requestData: {
          joinBrandId: id,
          themeActivityId: this.themeId
        }
      }
      return validCanDelBrand(params).then(res => {
        if (res.code == 0) {
          return res.data
        } else {
          this.$message.warning(res.msg)
          return false
        }
      })
    },
    // 上传图片
    /* getUploadParams() {
      return { ...globalData.uploadParams }
    }, */
    fileImageChange(list) {
      console.log('list', list)
      this.form.imgList = list.length > 0 ? list : undefined
    },
    onChange(value, dateString) {
      console.log('Selected Time: ', value)
      console.log('Formatted Selected Time: ', dateString)
    },
    onOk(value) {
      console.log('onOk: ', value, this.form.timePicker)
    },
    async removeBrands(item, key) {
      console.log(item, key, this.form)
      if (item == '') {
        this.form.brands.splice(key, 1)
        this.originBrands = JSON.parse(JSON.stringify(this.form.brands))
        return
      }

      if (this.themeId != 'add') {
        let result = await this.getValidCanDelBrand(this.originBrands[key])
        if (!result) {
          this.$message.warning('该品牌下已有关联搭配！')
          return
        }
      }
      let index = this.form.brands.indexOf(item)
      if (index !== -1) {
        this.form.brands.splice(index, 1)
      }
      this.originBrands = JSON.parse(JSON.stringify(this.form.brands))
      this.$forceUpdate()
    },
    addBrands() {
      this.form.brands.push('')
      this.$forceUpdate()
    },
    getChoose(item) {
      console.log(item)
      this.xcx = item
      this.form.materialId = item.id
      this.xcxImg = item.imgUrl
      this.xcxText = item.title
    },
    validatorImg(rule, value, callback) {
      if (this.form.imgList && this.form.imgList.length > 0) {
        callback()
      } else {
        callback('请上传封面图')
      }
    },
    validatorbrands(rule, value, callback) {
      if (value) {
        callback()
      } else {
        callback('请选择参与活动品牌')
      }
    },
    // 素材列表
    fetchMaterialList() {
      let params = {
        page: {
          pageNo: 1,
          pageSize: 100
        }
      }
      getMaterialList().then(res => {
        if (res.code == 0) {
          this.materialList = res.data
        }
      })
    },
    // 活动详情
    async fetchActivityDetail() {
      this.spinning = true
      let res = await this.fetchThemeActivityById(this.themeId)
      if (res.code == 0) {
        let formValue = res.data.bthemeActivity
        this.xcx = res.data.bwxMaterial
        this.form = {
          id: formValue.id,
          activityName: formValue.activityName,
          brands: formValue.joinBrandId.split(','),
          imgList: [formValue.coverPicture] || [],
          timePicker: formValue.startTime && formValue.endTime ? [moment(formValue.startTime), moment(formValue.endTime)] : [],
          materialId: formValue.materialId,
          miniAppShow: formValue.miniAppShow == 1 ? true : false,
          sortNo: formValue.sortNo
        }
        this.imgList = [formValue.coverPicture] || []
        if (this.xcx != null) {
          this.xcxImg = this.xcx.imgUrl
          this.xcxText = this.xcx.title
        }

        this.originBrands = formValue.joinBrandId.split(',')
      } else {
        this.$message.warning(res.msg)
      }
      this.spinning = false
    },
    async save() {
      if (this.form.materialId) {
        this.showwxTip = false
        let formValue = this.filterFields(this.form)
        console.log(formValue)
        let result = null
        if (this.themeId == 'add') {
          result = await this.addActivity(formValue)
        } else {
          result = await this.editActivity(formValue)
        }
        return result
      } else {
        this.showwxTip = true
        return false
      }
    },
    async submit() {
      let result = await this.save()
      if (result) {
        setTimeout(() => {
          this.$router.back()
        }, 200)
      }
    },
    async submitAndKeep() {
      let result = await this.save()
      if (result) {
        this.$router.push(`/box/operations/theme/lookList/${this.themeId}`)
      }
    },
    filterFields(values) {
      console.log(values)
      const formValue = {}
      Object.keys(values).forEach(i => {
        if (values[i] !== '' && values[i] !== undefined) {
          if (i === 'timePicker') {
            formValue.startTime = values[i][0].format('YYYY-MM-DD HH:mm:ss')
            formValue.endTime = values[i][1].format('YYYY-MM-DD HH:mm:ss')
          } else if (i == 'brands') {
            formValue.joinBrandId = values[i].join(',')
            let brandNames = []
            let brandIds = values[i]
            for (let item of brandIds) {
              let result = this.brandsList.filter(e => item == e.value)
              if (result.length > 0) brandNames.push(result[0].name)
            }
            formValue.joinBrandName = brandNames.join(',')
          } else if (i === 'imgList') {
            formValue.coverPicture = values[i][0].url
          } else if (i === 'xcxImg') {
            formValue.coverPicture = values[i][0].url
          } else if (i == 'miniAppShow') {
            formValue.miniAppShow = values[i] ? 1 : 0
          } else {
            formValue[i] = values[i]
          }
        }
      })
      return formValue
    },
    addActivity(formValue) {
      let params = {
        requestData: formValue
      }
      return addThemeActivity(params).then(res => {
        if (res.code == 0) {
          this.$message.success('创建成功！')
          this.themeId = res.data.id
          return true
        } else {
          this.$message.warning(res.msg)
          return false
        }
      })
    },
    editActivity(formValue) {
      let params = {
        requestData: { ...formValue, id: this.themeId }
      }
      return editThemeActivityById(params).then(res => {
        if (res.code == 0) {
          this.$message.success('编辑成功！')
          return true
        } else {
          this.$message.warning(res.msg)
          return false
        }
      })
    },
    openMaterial() {
      this.$refs.materialModal.show()
    }
  }
}
</script>
<style lang="less" scoped>
.steps-head {
  width: 60%;
  margin: 0 auto 24px;
  overflow: hidden;
}
.steps-content {
  min-height: 200px;
}
.steps-action {
  margin-top: 24px;
  display: flex;
  justify-content: center;
}
.xcx {
  display: flex;
  align-items: center;
  img {
    width: 150px;
    height: 150px;
    object-fit: scale-down;
    margin-right: 12px;
  }
  p {
    margin-right: 12px;
  }
  .tip {
    color: #f5222d;
    margin-left: 12px;
  }
}
.xcx-card {
  width: 224px;
  margin-right: 12px;
  .img-cover {
    height: 100%;
    width: 100%;
    object-fit: scale-down;
    border-bottom: 1px solid #e8e8e8;
    display: block;
  }
}

/deep/.xcx-card {
  .ant-card-cover {
    height: 180px;
  }
  .ant-card-body {
    min-height: 170px;
  }
  .ant-card-meta-title {
    color: rgba(0, 0, 0, 0.45);
    font-size: 14px;
    font-weight: normal;
  }
  .ant-card-meta-description {
    color: rgba(0, 0, 0, 0.85);
    font-weight: 500;
    font-size: 16px;
    word-wrap: break-word;
  }
}
.dynamic-delete-button {
  cursor: pointer;
  position: relative;
  top: 4px;
  font-size: 24px;
  color: #999;
  transition: all 0.3s;
}
.dynamic-delete-button:hover {
  color: #777;
}
.dynamic-delete-button[disabled] {
  cursor: not-allowed;
  opacity: 0.5;
}
</style>

